﻿public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class Solution
{
    public TreeNode SearchBST(TreeNode root, int val) {
        
        while (root is not null)
        {
            if (root.val == val) return root;
            else if (root.val < val) root = root.right;
            else  root = root.left;
        }

        return root;
    }

    public static void Main(string[] args)
    {
        int?[] root = [4, 2, 7, 1, 3];
        int val = 2;
        TreeNode t1 = CreateBinaryTree(root);

        Solution solution = new Solution();
        TreeNode node = solution.SearchBST(t1, val);
        PreOrderPrint(node);
    }
    private static TreeNode CreateBinaryTree(int?[] root)
    {
        if (root is null || root.Length == 0 || root[0] is null)
        {
            return null;
        }

        Queue<TreeNode> queue = new Queue<TreeNode>();
        TreeNode rootNode = new TreeNode(root[0].Value);
        queue.Enqueue(rootNode);
        int i = 1;
        TreeNode node;
        bool flag;

        while (i < root.Length && queue.Count > 0)
        {
            flag = true;
            node = queue.Dequeue();
            if (root[i] is not null)
            {
                flag = false;
                node.left = new TreeNode(root[i].Value);
                queue.Enqueue(node.left);
            }

            i++;
            if (i >= root.Length) break;
            if (root[i] is not null)
            {
                flag = false;
                node.right = new TreeNode(root[i].Value);
                queue.Enqueue(node.right);
            }
            i++;

            if (flag)
            {
                queue.Enqueue(node);
            }
        }

        return rootNode;
    }

    
    private static void PreOrderPrint(TreeNode rootNode)
    {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if (rootNode is not null) stack.Push(rootNode);
        TreeNode node;
        while (stack.Count > 0)
        {
            node = stack.Pop();
            Console.Write($"{node.val} ");
            if (node.right is not null) stack.Push(node.right);
            if (node.left is not null) stack.Push(node.left);
        }
    }
}